//
//  ViewController.m
//  hpple解析HTML
//
//  Created by Eric-Mac on 16/4/27.
//  Copyright © 2016年 JimmyStuido. All rights reserved.
//

#import "ViewController.h"
#import "TFHpple.h"
#import "TFHppleElement.h"

#define ContentHtml @"<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"renderer\" content=\"webkit\">\n    <meta name=\"format-detection\" content=\"telephone=no\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=Edge\">\n    <meta name=\"apple-mobile-web-app-capable\" content=\"yes\">\n    <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\">\n    <meta id=\"vp\" name=\"viewport\" content=\"width=device-width, user-scalable=no,maximum-scale=1.0,initial-scale=1\">\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"http://www.maimenghuo.com/static/web/apps/current/css/post_c682b94.css\">\n    <title>文章内容</title>\n    <script>\n    var _hmt = _hmt || [];\n    (function() {\n      var hm = document.createElement(\"script\");\n      hm.src = \"http://hm.baidu.com/hm.js?671ba6af32ea744361cf2ba8c989711b\";\n      var s = document.getElementsByTagName(\"script\")[0]; \n      s.parentNode.insertBefore(hm, s);\n    })();\n    </script>\n\n</head>\n<body>\n    <div class=\"wrapper\">\n        <div class=\"post\">\n            <div class=\"content\">\n                <p>蓝蓝的天空，白白的云，以及藏在云里的雨。柔柔绵绵的云朵君，像棉花糖般的美好。小时候最喜欢畅想自己长着翅膀在云里穿来穿去，触摸它们。萌萌兔特意找了云朵元素的小宝贝送给你们，圆你们一个童年的梦想~</p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">1</span><span class=\"ititle\">Doiy·云朵切菜器</span></h3>\r\n<p>大厨可不是人人都能当的，但每个人都幻想自己能切出整齐漂亮的菜。这个云朵切菜器可以帮你切出整齐的菜哦，新手使用最方便了，不会切到手。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/7s2lkd33v_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥49.99</span></p><p class=\"item-like-info\">75人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17124\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">2</span><span class=\"ititle\">云朵早餐垫</span></h3>\r\n<p>这个餐垫是不是很有意思呢？白色的云朵图案，很有创意呢。每天在云端吃饭也是很美好的一件事哦。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/dyk4ftl8o_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥45.00</span></p><p class=\"item-like-info\">28人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17125\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">3</span><span class=\"ititle\">云朵手机壳</span></h3>\r\n<p>恋上天空、爱上云朵，可不能拥有。这款手机壳是不是很云淡风轻呢，多美的云朵都可以在身边哦。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/3582hcz3f_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥68.90</span></p><p class=\"item-like-info\">37人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17126\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">4</span><span class=\"ititle\">云朵图案棒球帽</span></h3>\r\n<p>听说把朵朵漂浮的白云戴在头上，每天都会有好心情哦。小清新的棒球帽，很适合春天哦。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/3cohmyzvq_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥25.00</span></p><p class=\"item-like-info\">91人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17127\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">5</span><span class=\"ititle\">手工云朵陶瓷杯</span></h3>\r\n<p>这款杯子是不是很清新呢？它的设立灵感来源于天气，下雨闪电、晴天里的气球。有了它们，是不是喝水也变得更有意思了呢。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/3q9tnqs1u_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥55.00</span></p><p class=\"item-like-info\">71人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17128\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">6</span><span class=\"ititle\">小清新云朵帆布鞋</span></h3>\r\n<p>一缕缕云彩飘在蓝天上，你可以尽情的享受清新的空气。手绘云朵图案，刷鞋的时候，图案也不会掉色。穿上它，去拥抱春天吧。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/fi2rjwyop_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥89.00</span></p><p class=\"item-like-info\">74人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17129\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">7</span><span class=\"ititle\">刺绣云朵形流苏香囊</span></h3>\r\n<p>天上的朵朵白云是什么味儿的呢？也许这款香囊能告诉你。非常优雅、非常贵气的一款刺绣流苏香囊，把云朵的味道带在身边。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/wis407jw8_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥39.00</span></p><p class=\"item-like-info\">48人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17130\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">8</span><span class=\"ititle\">云朵抱枕</span></h3>\r\n<p>终于可以把天上的云朵抱在怀中了，软绵绵的触感，仿佛躺在云端上。抱一个回家吧。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/tiyn2fk7s_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥59.90</span></p><p class=\"item-like-info\">29人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17131\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">9</span><span class=\"ititle\">云朵iPhone手机壳</span></h3>\r\n<p>3D立体效果的云层，既壮观又唯美。喜欢云朵的文艺青年不要错过了哦。它有软硬两种壳可以选，带给你触觉与视觉的双重享受。<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/u3xan3360_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥49.80</span></p><p class=\"item-like-info\">10人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17132\" target=\"_blank\"><span>查看详情</span></a></div></p>\r\n<h3 class=\"item-title\"><span class=\"ititle-serial\">10</span><span class=\"ititle\">云朵鸡蛋挎包</span></h3>\r\n<p>云朵形的荷包蛋？这是一只包包哦，是不是很可爱，是不是很有食欲？看到这个包，你是不是想吃煎蛋了呢？<img src=\"http://7xkwn3.com1.z0.glb.clouddn.com/image/160418/v13uteroj_w.jpg-w720\" alt=\"\" /></p>\r\n<p><div class=\"item-info\"><p class=\"item-info-price\"><span style=\"font-family: arial;\">￥138.00</span></p><p class=\"item-like-info\">16人喜欢</p><a class=\"item-info-link\" href=\"http://www.maimenghuo.com/items/17133\" target=\"_blank\"><span>查看详情</span></a></div></p>\n                <div id=\"share-tip\" class=\"share-tip\"></div>\n            </div>\n        </div>\n    </div>\n\n    <script type=\"text/javascript\">var require,define;!function(e){function r(e,r){function t(){clearTimeout(a)}if(!(e in u)){u[e]=!0;var i=document.createElement(\"script\");if(r){var a=setTimeout(r,require.timeout);i.onerror=function(){clearTimeout(a),r()},\"onload\"in i?i.onload=t:i.onreadystatechange=function(){(\"loaded\"==this.readyState||\"complete\"==this.readyState)&&t()}}return i.type=\"text/javascript\",i.src=e,n.appendChild(i),i}}function t(e,t,n){var a=i[e]||(i[e]=[]);a.push(t);var o,u=s[e]||{},f=u.pkg;o=f?c[f].url:u.url||e,r(o,n&&function(){n(e)})}var n=document.getElementsByTagName(\"head\")[0],i={},a={},o={},u={},s={},c={};define=function(e,r){a[e]=r;var t=i[e];if(t){for(var n=0,o=t.length;o>n;n++)t[n]();delete i[e]}},require=function(e){if(e&&e.splice)return require.async.apply(this,arguments);e=require.alias(e);var r=o[e];if(r)return r.exports;var t=a[e];if(!t)throw\"[ModJS] Cannot find module `\"+e+\"`\";r=o[e]={exports:{}};var n=\"function\"==typeof t?t.apply(r,[require,r.exports,r]):t;return n&&(r.exports=n),r.exports},require.async=function(r,n,i){function o(e){for(var r=0,n=e.length;n>r;r++){var c=e[r];if(c in a){var f=s[c];f&&\"deps\"in f&&o(f.deps)}else if(!(c in l)){l[c]=!0,p++,t(c,u,i);var f=s[c];f&&\"deps\"in f&&o(f.deps)}}}function u(){if(0==p--){for(var t=[],i=0,a=r.length;a>i;i++)t[i]=require(r[i]);n&&n.apply(e,t)}}\"string\"==typeof r&&(r=[r]);for(var c=0,f=r.length;f>c;c++)r[c]=require.alias(r[c]);var l={},p=0;o(r),u()},require.resourceMap=function(e){var r,t;t=e.res;for(r in t)t.hasOwnProperty(r)&&(s[r]=t[r]);t=e.pkg;for(r in t)t.hasOwnProperty(r)&&(c[r]=t[r])},require.loadJs=function(e){r(e)},require.loadCss=function(e){if(e.content){var r=document.createElement(\"style\");r.type=\"text/css\",r.styleSheet?r.styleSheet.cssText=e.content:r.innerHTML=e.content,n.appendChild(r)}else if(e.url){var t=document.createElement(\"link\");t.href=e.url,t.rel=\"stylesheet\",t.type=\"text/css\",n.appendChild(t)}},require.alias=function(e){return e},require.timeout=5e3}(this);</script>\n    <script type=\"text/javascript\" src=\"http://www.maimenghuo.com/static/web/components/jquery/jquery_d107a7d.js\"></script>\n<script type=\"text/javascript\" src=\"http://www.maimenghuo.com/static/web/apps/current/js/post-content_35287f8.js\"></script>\n\n    <script>\n      require(\"current/post-content\");\n    </script>\n</body>\n</html>"

@interface ViewController ()<UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@property (nonatomic , strong)  NSMutableArray *itemIds;

@property (nonatomic , strong) NSURLRequest *request;

@end

@implementation ViewController

-(NSMutableArray *)itemIds
{
    if (!_itemIds) {
        _itemIds = [[NSMutableArray alloc]init];
    }
    return _itemIds;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"H5和Native交互";
    self.view.backgroundColor = [UIColor whiteColor];
//*********************点击cell解析得到contentHtml数据*****************//
    NSString *contentHtml  = ContentHtml;
    
    NSData *htmlData = [contentHtml dataUsingEncoding:NSUTF8StringEncoding];
    
    TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
    
    NSString *nodeString = @"//a[@class='item-info-link']";
    
    NSArray *element = [xpathParser searchWithXPathQuery:nodeString];
    
    for (TFHppleElement * e in element) {
        
        NSString *href = [e objectForKey:@"href"];
        
        NSRange range = [href rangeOfString:@"http://www.maimenghuo.com/items/"];
        
        if (range.location!=NSNotFound) {
            
            NSString *itemId = [href substringFromIndex:range.location+range.length];
            
            [self.itemIds addObject:itemId];//获得web页面的itemId
            
        }
    }
    
//*********************************加载WebView****************************//
    self.webView.delegate = self;
    
    NSURL *contentUrl = [[NSBundle mainBundle]URLForResource:@"http-::www.maimenghuo.com:posts:19698:content" withExtension:@"html"];//我吧这个H5源码保存在本地，示意一下。
    self.request = [NSURLRequest requestWithURL:contentUrl];
    
    [self.webView loadRequest:self.request];
    

}

//对H5源码动点手脚
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *ids = [self.itemIds componentsJoinedByString:@","];//转成js样式

//    拼接js语句
    NSString *jsStr = [NSString stringWithFormat:@"var itemIds = [%@]; var a = document.getElementsByClassName('item-info-link');console.log(a.length);for(var  i = 0; i < a.length ; i ++) {a[i].href=itemIds[i]}",ids];
    
    //执行
    [webView stringByEvaluatingJavaScriptFromString:jsStr];

    
}


-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[request.URL absoluteString] isEqualToString:[self.request.URL absoluteString]]) {
        
        return YES;
    }else
    {
        
        NSString *seletedItemId =[request.URL.absoluteString substringFromIndex:request.URL.absoluteString.length -5];
        
        [self pushViewControllerWithItemId:seletedItemId];
        
        return NO;
    }

}

//push出原生VC
-(void)pushViewControllerWithItemId:(NSString *)itemId
{
    UIViewController *vc = [[UIViewController alloc]init];
    
    vc.title = [NSString stringWithFormat:@"你点的itemId是%@",itemId];
    
    vc.view.backgroundColor = [UIColor whiteColor];
    
    [self.navigationController pushViewController:vc animated:YES];
}
@end
